// pages/ScenicArea/ScenicAreaChooseTickets/index.js
var common = require("../../../public.js");
var that
Page({

    /**
     * 页面的初始数据
     */
    data: {
        maxDay: new Date(2025, 0, 31).getTime(),
        date: '',
        show1: false,
        currentSelectTime: '',
        scenicTicketId: '',
        currentMonth: '', // 当前月份
        ticketPriceList: 1,
        allTicketPriceList: [],
        dateDisplayList: [], // 显示的三个时间 默认为获取到时间的前三项
        currenTicketDate: '', // 当前选中的票价
        timeList: [], // 入园时间
        enterInvoiceExplain: '', // 备注说明
        currentTime: '', //当前选中的入园时间
        ticketCount: 1, //票数量
        totalMoney: 0, // 总价
        showCalendar: false,
        formatter: '',
        isLoadingBusy: false,
        newArr: [], //截取后的日期
        dateFlag: true,  //日历选择
        numdis: true,
        discount:1,
        cardId: '',
        bookPreDays:'',
        bookFlag:'',
        todayNum:-1,
        storeType:'',
        // minDate: new Date(2023, 0, 1).getTime(),
        // maxDate: new Date(2024, 0, 31).getTime(),

    },

    onLoad: function (options) {
        // console.log(options, '4554555')
        let pages = getCurrentPages();
        let prevpage = pages[pages.length - 2];
        if (prevpage && prevpage.route && prevpage.route == "pages/goYuyue/yuYue/index") {
            this.setData({
                numdis: false
            })
        }
        that = this
      
        
        const title = options.storeName + '-' + options.ticketName
        wx.setNavigationBarTitle({ title })
        common.getLocalUserInfo(function (success, data) {
            if (success) {
                // console.log(options)
                that.setData({
                    isLoadingBusy: true,
                    userInfo: data.user,
                    token: data.token,
                    openid: data.openid,
                    currentMonth: common.dateFormat('yyyy-MM', new Date()),
                    scenicTicketId: options.ticketId,
                    storeId: options.storeId,
                    ticketName: options.ticketName,
                    storeName: options.storeName,
                    cardId: options.cardId ? options.cardId : '',
                    discount:options.discount ? parseFloat(options.discount) :1,
                    pid_name: options.pid_name ? options.pid_name : '',
                    ticketType: options.ticketSource,
                    bookPreDays:options.bookPreDays,
                    bookFlag:options.bookFlag,
                    storeType:options.storeType

                }, _ => {
                    // console.log('执行了');
                    that.initData('')
                })
            } else {
                common.showLoginPage()
            }
        })
    },
    onDisplay() {
        this.setData({ show1: true });
    },
    onClose() {
        this.setData({ show1: false });
    },
    formatDate(date) {
        date = new Date(date);
        return `${date.getMonth() + 1}/${date.getDate()}`;
    },
    // onConfirm(event) {
    //   this.setData({
    //     show1: false,
    //     date: this.formatDate(event.detail),
    //   });
    // },

    onConfirm(e) {
        this.setData({
            showCalendar: false
        })
        // if (this.data.showCalendar) {
        //   let current = common.dateFormat('yyyy-MM', e.detail)
        //   if (this.data.currentMonth != current) {
        //     this.setData({
        //       currentMonth: current,
        //     })
        //   }
        // }
    },
    initData(month) {
        // console.log('啊啊啊');
        let that = this
        let tempJson = {
            scenicTicketId: that.data.scenicTicketId,
            // searchMonth: that.data.currentMonth
            searchMonth: month,
            ticketType: that.data.ticketType
        }

        // common.post('/scenicTicket/getScenicTicketDatePriceList', tempJson,不用的
        common.post('/scenicTicket/getScenicTicketDatePriceListForApplet', tempJson,
            //  common.post('/scenicTicket/xcx/xcxScenicTicketDatePriceList', tempJson,
            function (res) {
                if (res.status === 200) {
                    // if(res.data.ticketPriceList.length){
                    //   console.log('currentMonth为',that.data.currentMonth);
                    //   // common.dateFormat('yyyy-MM', new Date())
                    //   // that.initData(parseInt(that.data.currentMonth)+1)
                    //   return;
                    // }
                    let dateDisplayList = []
                    // if (res.data.allTicketPriceList.length >= 3) {
                    //   dateDisplayList = [res.data.allTicketPriceList[0], res.data.allTicketPriceList[1], res.data.allTicketPriceList[2]]
                    // } else {
                    //   dateDisplayList = res.data.allTicketPriceList
                    // }


                    // var currentTimestamp = Date.parse(new Date()); 
                    // console.log('当天的时间戳为',currentTimestamp);// 2021-08-14 08:43:30
                    // var tempAllTicketPriceList = [];
                    // // 1天的时间戳86400000 

                    // for(var i = 0;i < res.data.allTicketPriceList.length;i++){
                    //   // 2021-08-14 00:00:00  2021-08-14 08:43:30
                    //   if(parseInt(res.data.allTicketPriceList[i].saleDate) + 86400000 >=currentTimestamp){
                    //     if(res.data.allTicketPriceList[i].saleDate>=currentTimestamp){
                    //       tempAllTicketPriceList.push(res.data.allTicketPriceList[i])
                    //     }
                    //   }

                    // }
                    // dateDisplayList = tempAllTicketPriceList
                    dateDisplayList = res.data.allTicketPriceList;
                    // console.log('嘻哈嘻哈', dateDisplayList);
                    var timeHour = new Date().getHours();
                    var Minutes = new Date().getMinutes();
                  
                    var timeNow = timeHour.toString() + ':' + Minutes.toString()
                    var Nowtime = that.time_to_sec(timeNow)
                   
                    var timeJava;
                    // console.log(that.data.todayNum,"454545454545")
                   if(that.data.todayNum==0){
                    for(var i=0;i<res.data.timeList.length;i++){

                        var javaTime = res.data.timeList[i].endTime
                        timeJava = that.time_to_sec(javaTime)
                        var resultTime = that.compareTime(timeJava, Nowtime)
                        res.data.timeList[i].timeFlag = resultTime
                    }
                   }
                  
                    // console.log(res.data,"打印大银幕 ")
                    that.setData({
                        allTicketPriceList: dateDisplayList,
                        timeList: res.data.timeList,
                        enterInvoiceExplain: res.data.enterInvoiceExplain ? res.data.enterInvoiceExplain : '',
                        // enterInvoiceExplain:'<p><strong>125555</strong></p>',
                        dateDisplayList
                    }, _ => {
                        that.setData({
                            formatter: function (day) {
                                // console.log('day为',day)
                                const year = day.date.getYear() +1;
                                // const year = day.date.getFullYear()
                                // var year = "20" + (day.date.getYear() - 100);	
                                // console.log('年份为---',year)
                                const month = day.date.getMonth()+1;
                                const date = day.date.getDate();
                                // console.log(month)
                                let list = dateDisplayList
                               
                                let monthList = list.map(item => {
                                
                                    return new Date(item.saleDate).getMonth() + 1
                                })
                                
                                monthList = Array.from(new Set(monthList))
                              
                                if (monthList.includes(month)) {
                                    let arr = list.filter(i => {
                                        // console.log()
                                        if(new Date(i.saleDate).getDate() == date && new Date(i.saleDate).getMonth() + 1 == month){
                                            return new Date(i.saleDate).getDate()
                                        }
                                        // return new Date(i.saleDate).getDate() == date
                                    })
                                    // console.log('arr为',arr);
                                   
                                    if (arr[0]) {
                                        if (arr[0].todayPrice < 0) {
                                            day.type = 'disabled'
                                            day.bottomInfo = '闭馆'
                                           
                                        } else {
                                            day.bottomInfo = '￥' + arr[0].todayPrice
                                        }
                                    } else {
                                        day.type = 'disabled'
                                    }

                                    // console.log(day,"44444")
                                    // for (let i = 0; i < list.length; i++) {
                                    //   const item = list[i];
                                    //   let saleMonth = new Date(item.saleDate).getMonth() + 1
                                    //   let saleDate = new Date(item.saleDate).getDate();
                                    //   if (month === saleMonth && date === saleDate) {
                                    //     day.bottomInfo = "￥" + item.todayPrice;
                                    //   }
                                    // }
                                } else {
                                    day.type = 'disabled'
                                }
                                return day
                            },
                        })
                    })
                }
            },
            function () {
                that.setData({
                    isLoadingBusy: false
                })
            })
    },
    time_to_sec(time) {
        // console.log(time, "hhhhhj")
        if (time !== null) {
          var s = "";
          var hour = time.split(":")[0];
          var min = time.split(":")[1];
          // var sec = time.split(":")[2];
          s = Number(hour * 3600) + Number(min * 60)
          return s;
        }
      },
      // 如果time2大于time1 返回true 否则 返回false
      compareTime(time2,time1) {
        if (time2 - time1 > 0) {
          return true;
        }else{
         return false;
        }
      },
    submitOrder() { //提交订单
        if (this.data.timeList.length == 1 && this.data.pid_name != '') {
            // console.log("进来了")
            this.setData({
                // currentTime: {
                //     index: 0,
                //     item: this.data.timeList[0]
                // }
            })
        }
        if (common.isEmptyString(this.data.currenTicketDate)) {
            common.showToast('请选择日期')
            return
        }
        if (common.isEmptyString(this.data.currentTime)) {
            common.showToast('请选择入园时间')
            return
        }
        if (this.data.currenTicketDate.item.saleDate < new Date(new Date(new Date().toLocaleDateString()).getTime())) {
            common.showToast('请选择正确日期')
            return
        }
        let enterDate = common.dateFormat('yyyy-MM-dd', this.data.currenTicketDate.item.saleDate)
        let enterWeekday = common.getWeekDate(this.data.currenTicketDate.item.saleDate)
        // console.log(enterWeekday)
        var money = this.data.discount == undefined ? this.data.currenTicketDate.item.todayPrice : this.data.currenTicketDate.item.todayPrice * parseFloat(this.data.discount)
        // console.log(money, "444444")
        // console.log(this.data.currenTicketDate.item, "this.data.currenTicketDate.item")
        wx.navigateTo({
            url: '/pages/ScenicArea/ScenicAreaCommitPage/index?storeId=' + this.data.storeId +
                '&ticketId=' + this.data.scenicTicketId +
                '&ticketName=' + this.data.ticketName +
                '&storeName=' + this.data.storeName +
                '&ticketPrice=' + money +
                '&ticketNum=' + this.data.ticketCount +
                '&ticketTimeId=' + this.data.currentTime.item.id +
                '&enterDate=' + enterDate +
                '&enterWeekday=' + enterWeekday +
                '&startTime=' + this.data.currentTime.item.startTime +
                '&endTime=' + this.data.currentTime.item.endTime +
                '&cardId=' + this.data.cardId +
                '&storeType=' + this.data.storeType +
                '&xcTimeId=' + this.data.currenTicketDate.item.xcTimeId,
        })
    },
    selectDate(e) {
        // console.log(e.currentTarget.dataset, "11145555")
        this.initData('')
        let index = e.currentTarget.dataset.index
        if(this.data.bookFlag==2 &&this.data.bookPreDays){
            if(index==0 || index==1){
                common.showToast('须提前两天订')
                return
            }
        }
        if (e.currentTarget.dataset.item.canSale == 1) {
            wx.showToast({
                title: '今日售罄',
                icon: 'none'
            })
            return
        }
        let currentObj = e.currentTarget.dataset
        // console.log(that.data.discount)
        // console.log('11~~~~', currentObj)
        if (currentObj.item.todayPrice < 0) {
            common.showToast('当日闭馆')
            return
        }
        var monet = this.data.discount == undefined ?
            currentObj.item.todayPrice * 100 * this.data.ticketCount :
            currentObj.item.todayPrice * 100 * this.data.ticketCount * parseFloat(this.data.discount)       //判断从哪个地方来的 parseInt(this.data.discount) 
        // console.log(parseFloat(this.data.discount,"5555555555555555555555fgbdbdbdbdbdbdbdbdbdbdbd"))
        // console.log(currentObj,"currenTicketDate")
        if(that.data.currentTime ){
            var obj =that.data.currentTime.index=''
        }
        
        this.setData({
            currentTime:obj,
            currenTicketDate: currentObj,
            totalMoney: monet,
            todayNum:index, //用于判断是否是今天
        })
    },
    selectTime(e) { //点击选择入园时间
        let currentObj = e.currentTarget.dataset
      
        if(currentObj.item.timeFlag==false){
            common.showToast('当前时间不可选择')
            return
        }
        this.setData({
            currentTime: currentObj
        })
    },
    selectCalendar(e) {
        let selectedYear = e.detail.getFullYear()
        let selectedDate = e.detail.getDate()
        let selectedMonth = e.detail.getMonth()
        // console.log('选择日期---', e, '年份', selectedYear, 'hhhhh', selectedDate);
        let serveTime = this.data.allTicketPriceList
        let arr = serveTime.filter(i => {
            return new Date(i.saleDate).getDate() == selectedDate && new Date(i.saleDate).getMonth() == selectedMonth
        })

        for (var i = 0; i < this.data.dateDisplayList.length; i++) {
            var saleDates = this.data.dateDisplayList[i].saleDate
            if (arr[0].saleDate == saleDates) {
                // console.log(this.data.dateDisplayList.slice(i - 1))  //选中的数组
                var newArr = []
                newArr = this.data.dateDisplayList.slice(i)
            }
        }

        this.setData({
            dateFlag: false,
            newArr: newArr,
            currenTicketDate: {
                // index: e.index,
                index: 0,
                item: arr[0],
            },
            // dateDisplayList: [this.data.dateDisplayList[0], this.data.dateDisplayList[1], arr[0]],
            totalMoney: arr[0].todayPrice * 100 * this.data.ticketCount,
            currentSelectTime: selectedYear + '.' + (parseInt(selectedMonth) + 1) + '.' + selectedDate
        }, _ => {
            this.setData({
                // showCalendar: false
            })
        })

    },

    // openCalendarSelect(e) {
    //   let selectedYear = e.detail.getFullYear()
    //   let selectedDate = e.detail.getDate()
    //   let selectedMonth = e.detail.getMonth()
    //   console.log('选择日期---',e,'年份',selectedYear,'hhhhh',selectedDate);
    //   let serveTime = this.data.allTicketPriceList
    //   let arr = serveTime.filter(i => {
    //     return new Date(i.saleDate).getDate() == selectedDate && new Date(i.saleDate).getMonth() == selectedMonth
    //   })
    //   this.setData({
    //     totalMoney: arr[0].todayPrice * 100 * this.data.ticketCount,
    //     currentSelectTime:selectedYear + '.' + (parseInt(selectedMonth) + 1) + '.' + selectedDate
    //   }, _ => {
    //     this.setData({
    //       // showCalendar: false
    //     })
    //   })
    // },

    // 选择日期
    openCalendar() {
        this.setData({
            showCalendar: true
        })
    },

    onCloseCalendar() {
        this.setData({
            showCalendar: false
        })
    },
    onCountChange(e) {
        if (this.data.currenTicketDate) {
            const num = e.detail
            this.setData({
                ticketCount: num,
                totalMoney: num * this.data.currenTicketDate.item.todayPrice * 100 // 单位分
            })
        } else {
            this.setData({
                ticketCount: 1
            })
            common.showToast('请先选择日期')
        }
    },
    onShareTimeline() {
        return {
            title: '飞羊精选',
            query: 'ticketId=' + this.data.scenicTicketId + '&storeId=' + this.data.storeId,

            imageUrl: 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/xfj/share.jpg',
            success: (res) => { },
            fail: (res) => {
                // 分享失败
            }
        }
    }
})